/**
 * Load an asynchronous script (identified by an url). When the url returns, the
 * content of this file is added into a new script element, attached to the DOM (body element)
 * @param scriptUrl defines the url of the script to laod
 * @returns a promise request object
 */
export function LoadScriptAsync(scriptUrl: string): Promise<void>
{
    return new Promise((resolve, reject) =>
    {
        LoadScript(
            scriptUrl,
            () =>
            {
                resolve();
            },
            (message: string, exception: any) =>
            {
                reject(exception || new Error(message));
            }
        );
    });
}

declare function importScripts(...urls: string[]): void;

/**
 * Load a script (identified by an url). When the url returns, the
 * content of this file is added into a new script element, attached to the DOM (body element)
 * @param scriptUrl defines the url of the script to laod
 * @param onSuccess defines the callback called when the script is loaded
 * @param onError defines the callback to call if an error occurs
 * @param scriptId defines the id of the script element
 */
function LoadScript(scriptUrl: string, onSuccess: () => void, onError?: (message?: string, exception?: any) => void, scriptId?: string)
{
    if (typeof importScripts === 'function')
    {
        try
        {
            console.log(1);
            importScripts(scriptUrl);
            onSuccess();
        }
        catch (e)
        {
            onError?.(`Unable to load script '${scriptUrl}' in worker`, e);
        }

        return;
    }
    else if (typeof window === 'undefined')
    {
        onError?.(`Cannot load script '${scriptUrl}' outside of a window or a worker`);

        return;
    }

    const head = document.getElementsByTagName('head')[0];
    const script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', scriptUrl);
    if (scriptId)
    {
        script.id = scriptId;
    }

    script.onload = () =>
    {
        if (onSuccess)
        {
            onSuccess();
        }
    };

    script.onerror = (e) =>
    {
        if (onError)
        {
            onError(`Unable to load script '${scriptUrl}'`, e);
        }
    };

    head.appendChild(script);
}
